<template>
  <Transition :duration="duration"
              @before-enter="beforeEnter"
              @enter="enter"
              @after-enter="afterEnter"
              @before-leave="beforeLeave"
              @leave="leave"
              @after-leave="afterLeave">
      <slot>
        <div/>
      </slot>
  </Transition>
</template>
<script lang="ts" setup>
import {nextTick, PropType} from "vue";

const props = defineProps({
  position: {
    type: String as PropType<'left' | 'right'>,
    default: 'left'
  },
  duration: {
    type: Number,
    default: 200
  }
})

defineOptions({
  name: 'FadeAnimation'
})

function beforeEnter(el: any) {
  el.style.opacity = '0.3'
  el.style.transform = 'scale(0.5)'
  el.style.transformOrigin = 'scale(0.5)'
  el.style.transition = `all ${props.duration}ms ease-in-out`
}

function enter(el: any) {
  nextTick(() => {
    el.style.opacity = '1'
    el.style.transform = 'scale(1)'
  })
}

function beforeLeave(el:any) {
  el.style.opacity = '1'
  el.style.transform = 'scale(1)'
  el.style.transformOrigin = 'scale(0.5)'
  el.style.transition = `all ${props.duration}ms ease-in-out`
}

function leave(el: any) {
  nextTick(() => {
    el.style.transform = 'scale(0.5)'
    el.style.opacity = '0'
  })
}

function afterLeave(el: any) {
  nextTick(() => {
    el.style.removeProperty('transition');
    el.style.removeProperty('opacity');
    el.style.removeProperty('transform');
    el.style.removeProperty('transformOrigin');
  })
}

function afterEnter(el: any) {
  nextTick(() => {
    el.style.removeProperty('transition');
    el.style.removeProperty('opacity');
    el.style.removeProperty('transform');
    el.style.removeProperty('transformOrigin');
  })
}
</script>